package com.gxa.employment.common;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.gxa.employment.entity.dto.StudentImportDto;
import com.gxa.employment.entity.pojo.Student;
import com.gxa.employment.service.StudentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义监听器，用于处理学生信息的导入
 */
public class StudentDataListener extends AnalysisEventListener<StudentImportDto> {
    private final StudentService studentService;
    private List<StudentImportDto> failedRecords = new ArrayList<>();

    public StudentDataListener(StudentService studentService) {
        // 将传入的StudentService赋值给类的成员变量studentService
        this.studentService = studentService;
    }


    @Override
    public void invoke(StudentImportDto studentDto,AnalysisContext context) {
        Student student = new Student();
        BeanUtils.copyProperties(studentDto,student);
        try {
            // 调用studentService的save方法保存学生信息
            studentService.save(student);
        } catch (Exception e) {
            // 如果出现异常，则将studentDto添加到failedRecords中
            failedRecords.add(studentDto);
        }
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 如果存在失败的记录
        if (!failedRecords.isEmpty()) {
            // 输出失败的记录数量
            System.out.println("Failed to import " + failedRecords.size() + " records.");
        }
    }


    public List<StudentImportDto> getFailedRecords() {
        // 返回失败的记录列表
        return failedRecords;
    }

}
